/*
 * @Author: Wangtao
 * @Date: 2022-08-09 14:11:35
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-09-20 13:35:40
 */
// 拖拽的指令
function mousedownFnWrap(x: any, y: any, dragable: any) {
  // 初次渲染时，top和left的位置
  let baseX = x, baseY = y
  // 鼠标按下事件
  return function mousedownFn(event: any) {
    if (!(event.target && event.target.attributes && event.target.attributes.drag)) {
      return
    }
    const startX = event.clientX
    const startY = event.clientY
    const bodyWidth = document.body.clientWidth
    const bodyHeight = document.body.clientHeight
    // 鼠标移动事件
    const move = (event: any) => {
      let top = baseY + event.clientY - startY
      let left = baseX + event.clientX - startX
      if (top < 0) {
        top = 0
      } else if (top + 50 >= bodyHeight) {
        top = bodyHeight - 50
      }
      if (left < 0) {
        left = 0
      } else if (left > (bodyWidth - 320)) {
        left = bodyWidth - 320
      }

      dragable.style.top = `${top}px`
      dragable.style.left = `${left}px`
    }
    // 鼠标抬起事件
    const up = (event: any) => {
      baseX = baseX + event.clientX - startX
      baseY = baseY + event.clientY - startY
      document.removeEventListener('mousemove', move)
      document.removeEventListener('mouseup', up)
    }
    document.addEventListener('mousemove', move)
    document.addEventListener('mouseup', up)
  }
}
const drag = {
  beforeMount(el: any, binding: any) {
    const baseX = binding && binding.value && binding.value.left ? binding.value.left : 0
    const baseY = binding && binding.value && binding.value.top ? binding.value.top : 0
    el.style.top = `${baseY}px`
    el.style.left = `${baseX}px`
    el.style.cssText += ';position:fixed;'
    const mousedownFn = mousedownFnWrap(baseX, baseY, el)
    el.__mousedownFn__ = mousedownFn
    console.log(el, 'ooooooooooooooooooooooooooooooooooooooooo')
    el.addEventListener('mousedown', mousedownFn)
  }
}
// 全局 挂载，注册
// const directives = {
//   install: function (app: any) {
//     app.directive('dialogDrag', drag)
//   }
// };
export default drag